import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * User: yunai
 * Date: 13-3-16
 * Time: 上午11:16
 * To change this template use File | Settings | File Templates.
 */
public class Main {

    private static Semaphore semaphore;

    private static class MyCallable implements Callable<Integer> {

        private int i;

        public MyCallable(int i) {
            this.i = i;
        }

        @Override
        public Integer call() throws Exception {
            System.out.println("线程：" + i + "开始");
            Thread.sleep(2000);
            System.out.println("线程：" + i + "结束");
            semaphore.release();
            return i;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        System.out.println("----程序开始运行----");
        Date date1 = new Date();

        int taskSize = 5;

        semaphore = new Semaphore(taskSize + 1);

        // 创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);
        // 创建多个有返回值的任务
//        List<Future<List<String>>> list = new ArrayList<Future<List<String>>>();
        List<Future<Integer>> list = new ArrayList<Future<Integer>>();
        int result = 0;
        for (int i = 0; i < taskSize; i++) {
            Callable<Integer> c = new MyCallable(i);
            // 执行任务并获取Future对象
            Future<Integer> f = pool.submit(c);
//            result += f.get();
            list.add(f);
        }

        semaphore.release();

        for (Future<Integer> f : list) {
            result += f.get();
        }
        // 关闭线程池
//        pool.shutdown();

        System.out.println(result);

//        Executors.newScheduledThreadPool()
    }
}
